<script setup>
import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
import SuyCpxc from '@/views/SuyManage/SuyCpxc/SuyCpxc.vue'
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
import api from '@/api/index.js'
import UploadFile from '@/components/UploadFile/UploadFile.vue'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  productPromotionId: '',
  name: '',
  variety: '',
  areaName: '',
  startTime: '',
  endTime: '',
  pickDate: [],
  pickDate1: [],
  items: []
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  (val) => {
    if (props.curRow.id && show.value) {
      formData.value = {
        ...formData.value,
        ...val,
        pickDate: [val.startTime, val.endTime],
        pickDate1: [val.advertStartTime, val.advertEndTime],
        items: val.items.map((item) => ({
          ...item,
          pickDate: [item.startTime, item.endTime],
          pickDate1: [item.advertStartTime, item.advertEndTime]
        }))
      }
    } else {
      formData.value = {
        productPromotionId: '',
        name: '',
        variety: '',
        areaName: '',
        startTime: '',
        endTime: '',
        pickDate: [],
        pickDate1: [],
        items: []
      }
    }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      productPromotionId: '',
      name: '',
      variety: '',
      areaName: '',
      startTime: '',
      endTime: '',
      pickDate: [],
      pickDate1: [],
      items: []
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      startTime: formData.value?.pickDate?.[0] || '',
      endTime: formData.value?.pickDate?.[1] || '',
      advertStartTime: formData.value?.pickDate1?.[0] || '',
      advertEndTime: formData.value?.pickDate1?.[1] || '',
      items: info.items.map((item) => ({
        ...item,
        startTime: item?.pickDate?.[0] || '',
        endTime: item?.pickDate?.[1] || ''
      }))
    }
    await api.editZl(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      startTime: formData.value?.pickDate?.[0] || '',
      endTime: formData.value?.pickDate?.[1] || '',
      advertStartTime: formData.value?.pickDate1?.[0] || '',
      advertEndTime: formData.value?.pickDate1?.[1] || '',
      items: info.items.map((item) => ({
        ...item,
        startTime: item?.pickDate?.[0] || '',
        endTime: item?.pickDate?.[1] || ''
      }))
    }
    await api.addZl(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })

const removeCg = (index) => {
  formData.value.items.splice(index, 1)
}
const addCg = () => {
  formData.value.items.push({
    name: '',
    startTime: '',
    endTime: '',
    img: '',
    pickDate: []
  })
}
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="选择产品宣传"
        name="productPromotionId"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-form-item-rest>
          <SltFromTable
            v-model="formData.productPromotionId"
            :component="SuyCpxc"
            :nameValue="formData.cropsName"
            :fieldNames="{ name: 'cropsName', id: 'id' }"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item label="作物品种" name="variety" :rules="[{ required: true, message: '请选择' }]">
        <a-input v-model:value="formData.variety" allowClear />
      </a-form-item>
      <a-form-item
        label="种植位置"
        name="areaName"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-input v-model:value="formData.areaName" allowClear />
      </a-form-item>
      <a-form-item
        label="种植时间"
        name="pickDate"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-range-picker
          v-model:value="formData.pickDate"
          valueFormat="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item
        label="宣传时间"
        name="pickDate1"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-range-picker
          v-model:value="formData.pickDate1"
          valueFormat="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item label="作业类别" name="items" :rules="{ required: true, message: '请填写完整' }">
        <a-space v-for="(item, index) in formData.items" :key="index" class="item" align="baseline">
          <a-form-item
            label="作业名称"
            :name="['items', index, 'name']"
            :rules="{ required: true, message: '请输入' }"
          >
            <a-input class="com-ipt" v-model:value="item.name" />
          </a-form-item>
          <a-form-item
            label="作业时间"
            :name="['items', index, 'pickDate']"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-range-picker
              class="com-ipt"
              v-model:value="item.pickDate"
              valueFormat="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item
            label="作业照片"
            :name="['items', index, 'img']"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-form-item-rest>
              <UploadFile v-model="item.img" :limit="1" />
            </a-form-item-rest>
          </a-form-item>
          <MinusCircleOutlined
            @click="removeCg(index)"
            style="position: absolute; right: 10px; top: 10px; color: red"
          />
        </a-space>
      </a-form-item>
      <a-form-item>
        <a-button type="dashed" block @click="addCg"> <PlusOutlined /> 新增消耗物资 </a-button>
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<style lang="scss" scoped>
.item {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  padding-bottom: 0;
  background-color: #eee;
  margin-bottom: 10px;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
}
</style>
